package cn.org.qary.controller.rking.back;

import cn.org.qary.entity.AddressInfo;
import cn.org.qary.entity.User;
import cn.org.qary.service.trait.rking.AddressInfoService;
import cn.org.qary.service.trait.rking.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.vavr.Tuple2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("back_user")
public class BackUserController {
    @Autowired
    UserService userService;

    @Autowired
    AddressInfoService addressInfoService;


    /**
    * 显示所有的用户信息到后端界面
    *
    * */
    int rows=3;
    @RequestMapping("show/{page}")
    public String findAll(@PathVariable(required = false) Integer page, Model model){
        if (page==null) page=1;
        Page<Object> pages = PageHelper.startPage(page, rows);
        List<User> userList = userService.selectAll();

        List<Tuple2<User, AddressInfo>> tuple2List =
                userList
                        .stream()
                        .map(u -> new Tuple2<>(u, addressInfoService.getFirstOne(u.getId())))
                        .collect(Collectors.toList());

          //等价于上面的代码，方便以后理解
//        List<Tuple2<User, AddressInfo>> aList = new ArrayList<>();
//        for (User u : userList) {
//            AddressInfo firstOne = addressInfoService.getFirstOne(u.getId());
//            Tuple2<User, AddressInfo> tempTuple2 = new Tuple2<>(u, firstOne);
//            aList.add(tempTuple2);
//        }

        System.out.println("tuple2List----------------"+tuple2List);

        model.addAttribute("userList",tuple2List);

        model.addAttribute("pages",pages);
        return "manage/user";
    }

    @RequestMapping("add")
    public String addUser(User user){
        userService.insert(user);
        return "redirect:show/1";
    }


    @RequestMapping("showOne/{id}")
    public String showOne(@PathVariable Integer id,Model model){
        User user = userService.selectById(id);
        model.addAttribute("user",user);
        return "manage/user-modify";
    }

    @RequestMapping("update")
    public String updateUser(User user){
        userService.update(user);
        return "redirect:show/1";
    }

    /**
     * 用于拿到后台首页的管理员数据
     */
    @RequestMapping("toIndex/{id}")
    public String toIndex(@PathVariable Integer id,Model model){
        User user = userService.selectById(id);
        model.addAttribute("user",user);
        return "manage/index";
    }
}
